﻿using BLL.Enums;
using DevExpress.Data.Filtering;
using DevExpress.Xpo;
using Model;
using Model.Bill;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BLL
{
    public class OrderDetailBLL
    {
        public void Add(TB_Order order, string warehouseID, string productID, ProductType productType, decimal quantity, decimal turnoverPrice)
        {
            Session s = order.Session;
            TB_OrderDetail od = null;
            bool flag = true;
            switch ((OrderType)order.TypeID)
            {
                case OrderType.Rack:
                    flag = MemberInfo.UserPosSetUp.StoreSaleDetailMerge;
                    break;
                case OrderType.Delivery:
                    flag =  MemberInfo.UserPosSetUp.DeliverySaleDetailMerge;;
                    break;
            }
            if (flag)
            {
                od = s.FindObject<TB_OrderDetail>(CriteriaOperator.Parse("OrderID=? And WarehouseID=? And ProductID=? And ProductType=?",
                    order, warehouseID, productID, productType));
                if (od != null)
                {
                    od.Quantity = od.Quantity + quantity;
                    od.SalePrice = turnoverPrice;
                    od.TurnoverPrice = turnoverPrice;
                    od.TurnoverAmount = od.Quantity * od.TurnoverPrice;
                    od.SalePriceLowest = od.ProductID.SalePriceLowest;
                    od.CostPrice = od.ProductID.CostPrice;
                    od.Save();
                    return;
                }
            }
            od = new TB_OrderDetail(s);
            od.OrderID = order;
            od.WarehouseID = s.GetObjectByKey<B_Warehouse>(warehouseID);
            od.ProductID = s.GetObjectByKey<P_Product>(productID);
            od.ProductType = (int)productType;
            od.Quantity = quantity;
            od.SalePrice = turnoverPrice;
            od.TurnoverPrice = turnoverPrice;
            od.TurnoverAmount = od.Quantity * od.TurnoverPrice;
            od.SalePriceLowest = od.ProductID.SalePriceLowest;
            od.CostPrice = od.ProductID.CostPrice;
            od.Save();

            CalcAmount(order);
        }
        /// <summary>
        /// 计算订单金额
        /// </summary>
        /// <param name="order"></param>
        public void CalcAmount(TB_Order order) 
        {
            order.CopeAmount = 0;
            order.LowestAmount = 0;
            foreach (TB_OrderDetail od in order.OrderDetails) {
                order.CopeAmount += od.Quantity * od.TurnoverPrice;
                order.LowestAmount += od.Quantity * od.SalePriceLowest;
            }
            order.Save();
        }
    }
}
